<template>
  <page-header-wrapper
    title="无人机实时监控"
    content="实时查看无人机飞行状态和配送过程，支持多机位监控和关键数据展示。"
  >
    <div class="live-broadcast-container">
      <a-row :gutter="16">
        <a-col :span="18">
          <a-card :bordered="false" class="main-video-card">
            <div class="video-header">
              <div class="video-title">
                <a-tag color="blue">{{ currentDrone.status }}</a-tag>
                {{ currentDrone.name }} - {{ currentDrone.id }}
              </div>
              <div class="video-controls">
                <a-button-group>
                  <a-button icon="camera" @click="takeSnapshot">截图</a-button>
                  <a-button icon="video-camera" :type="isRecording ? 'danger' : 'default'" @click="toggleRecording">
                    {{ isRecording ? '停止录制' : '开始录制' }}
                  </a-button>
                  <a-button icon="fullscreen" @click="toggleFullscreen">全屏</a-button>
                </a-button-group>
              </div>
            </div>

            <div class="main-video-container" ref="mainVideoContainer">
              <div class="video-overlay">
                <div class="overlay-item overlay-time">{{ currentTime }}</div>
                <div class="overlay-item overlay-coordinates">
                  经度: {{ currentDrone.longitude.toFixed(6) }} | 纬度: {{ currentDrone.latitude.toFixed(6) }}
                </div>
                <div class="overlay-item overlay-altitude">高度: {{ currentDrone.altitude }}m</div>
                <div class="overlay-item overlay-speed">速度: {{ currentDrone.speed }}km/h</div>
                <div class="overlay-item overlay-battery">
                  <a-icon type="battery" /> {{ currentDrone.battery }}%
                </div>
                <div class="overlay-item overlay-signal">
                  <a-icon type="wifi" /> {{ currentDrone.signalStrength }}%
                </div>
              </div>
              <video
                ref="mainVideo"
                class="main-video"
                :src="currentDrone.videoUrl"
                autoplay
                loop
                muted
                @click="togglePlayPause"
              ></video>
              <div v-if="!isPlaying" class="play-overlay">
                <a-icon type="play-circle" @click="togglePlayPause" />
              </div>
            </div>

            <div class="video-info">
              <a-descriptions :column="3" size="small">
                <a-descriptions-item label="订单编号">{{ currentDrone.orderSn }}</a-descriptions-item>
                <a-descriptions-item label="配送地址">{{ currentDrone.destination }}</a-descriptions-item>
                <a-descriptions-item label="预计到达">{{ currentDrone.eta }}</a-descriptions-item>
                <a-descriptions-item label="飞行时间">{{ currentDrone.flightTime }}</a-descriptions-item>
                <a-descriptions-item label="剩余电量">{{ currentDrone.battery }}%</a-descriptions-item>
                <a-descriptions-item label="信号强度">{{ currentDrone.signalStrength }}%</a-descriptions-item>
              </a-descriptions>
            </div>
          </a-card>
        </a-col>

        <a-col :span="6">
          <a-card :bordered="false" title="无人机列表" class="drone-list-card">
            <a-radio-group v-model="filterStatus" button-style="solid" style="margin-bottom: 16px;">
              <a-radio-button value="">全部</a-radio-button>
              <a-radio-button value="飞行中">飞行中</a-radio-button>
              <a-radio-button value="待机中">待机中</a-radio-button>
            </a-radio-group>

            <div class="drone-list">
              <a-list
                :dataSource="filteredDrones"
                :loading="loading"
                size="small"
              >
                <a-list-item slot="renderItem" slot-scope="item" @click="selectDrone(item)" :class="{'active-drone': currentDrone.id === item.id}">
                  <a-list-item-meta>
                    <div slot="title">
                      <a-tag :color="getStatusColor(item.status)">{{ item.status }}</a-tag>
                      {{ item.name }}
                    </div>
                    <div slot="description">
                      <div>订单: {{ item.orderSn || '无' }}</div>
                      <div>电量: {{ item.battery }}% | 信号: {{ item.signalStrength }}%</div>
                    </div>
                    <a-avatar
                      slot="avatar"
                      :src="item.thumbnailUrl"
                      shape="square"
                      size="large"
                    />
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
            </div>
          </a-card>

          <a-card :bordered="false" title="飞行数据" class="flight-data-card" style="margin-top: 16px;">
            <a-row :gutter="[16, 16]">
              <a-col :span="12">
                <a-statistic
                  title="当前高度"
                  :value="currentDrone.altitude"
                  :precision="1"
                  suffix="m"
                />
              </a-col>
              <a-col :span="12">
                <a-statistic
                  title="当前速度"
                  :value="currentDrone.speed"
                  :precision="1"
                  suffix="km/h"
                />
              </a-col>
              <a-col :span="12">
                <a-statistic
                  title="已飞行"
                  :value="currentDrone.distanceTraveled"
                  :precision="1"
                  suffix="km"
                />
              </a-col>
              <a-col :span="12">
                <a-statistic
                  title="剩余距离"
                  :value="currentDrone.distanceRemaining"
                  :precision="1"
                  suffix="km"
                />
              </a-col>
            </a-row>

            <a-divider style="margin: 16px 0" />

            <div class="flight-actions">
              <a-button-group style="width: 100%;">
                <a-button type="primary" icon="message" style="width: 50%;" @click="handleContact">联系操作员</a-button>
                <a-button type="danger" icon="warning" style="width: 50%;" @click="showEmergencyModal">紧急召回</a-button>
              </a-button-group>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <a-row :gutter="16" style="margin-top: 16px;">
        <a-col :span="24">
          <a-card :bordered="false" title="多机位监控" class="multi-view-card">
            <div class="multi-view-container">
              <div
                v-for="drone in activeDrones"
                :key="drone.id"
                class="mini-video-container"
                @click="selectDrone(drone)"
                :class="{'active-mini-video': currentDrone.id === drone.id}"
              >
                <video
                  :src="drone.videoUrl"
                  class="mini-video"
                  autoplay
                  loop
                  muted
                ></video>
                <div class="mini-video-overlay">
                  <div class="mini-video-title">
                    <a-tag :color="getStatusColor(drone.status)" size="small">{{ drone.status }}</a-tag>
                    {{ drone.name }}
                  </div>
                  <div class="mini-video-info">
                    订单: {{ drone.orderSn || '无' }} | 电量: {{ drone.battery }}%
                  </div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <a-modal
        title="截图保存"
        :visible="snapshotVisible"
        @cancel="snapshotVisible = false"
        :footer="null"
      >
        <div class="snapshot-container">
          <img :src="snapshotUrl" alt="截图" style="width: 100%;" />
          <div style="margin-top: 16px;">
            <a-form layout="vertical">
              <a-form-item label="截图名称">
                <a-input v-model="snapshotName" placeholder="请输入截图名称" />
              </a-form-item>
              <a-form-item label="备注">
                <a-textarea v-model="snapshotRemark" placeholder="请输入备注信息" :rows="3" />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" block @click="saveSnapshot">保存截图</a-button>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </a-modal>

      <a-modal
        title="联系操作员"
        :visible="contactVisible"
        @cancel="contactVisible = false"
        :footer="null"
      >
        <div class="contact-container">
          <a-descriptions :column="1">
            <a-descriptions-item label="操作员姓名">{{ currentDrone.operatorName }}</a-descriptions-item>
            <a-descriptions-item label="联系电话">{{ currentDrone.operatorPhone }}</a-descriptions-item>
          </a-descriptions>
          <a-divider />
          <a-form layout="vertical">
            <a-form-item label="消息内容">
              <a-textarea v-model="contactMessage" placeholder="请输入消息内容" :rows="4" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" block @click="sendMessage">发送消息</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>

      <a-modal
        title="紧急召回确认"
        :visible="emergencyModalVisible"
        :confirmLoading="emergencyLoading"
        @ok="handleEmergencyConfirm"
        @cancel="handleEmergencyCancel"
        okText="确认召回"
        cancelText="取消"
        okType="danger"
      >
        <a-alert
          message="警告：紧急召回操作"
          description="此操作将中断当前任务，强制无人机返回起飞点。请确认是否执行此操作？"
          type="warning"
          show-icon
          style="margin-bottom: 16px;"
        />

        <a-form-item label="召回原因">
          <a-select v-model="emergencyReason" placeholder="请选择召回原因" style="width: 100%">
            <a-select-option value="weather">恶劣天气</a-select-option>
            <a-select-option value="malfunction">设备故障</a-select-option>
            <a-select-option value="battery">电量不足</a-select-option>
            <a-select-option value="safety">安全隐患</a-select-option>
            <a-select-option value="other">其他原因</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item v-if="emergencyReason === 'other'" label="详细说明">
          <a-textarea v-model="emergencyDescription" placeholder="请输入详细原因" :rows="4" />
        </a-form-item>

        <a-form-item label="紧急程度">
          <a-radio-group v-model="emergencyLevel">
            <a-radio value="high">
              <a-tag color="red">高</a-tag> 立即返航
            </a-radio>
            <a-radio value="medium">
              <a-tag color="orange">中</a-tag> 完成当前动作后返航
            </a-radio>
            <a-radio value="low">
              <a-tag color="blue">低</a-tag> 安全地点降落
            </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="操作确认">
          <a-checkbox v-model="emergencyConfirmed">
            我已了解紧急召回的后果，并确认执行此操作
          </a-checkbox>
        </a-form-item>
      </a-modal>

      <a-modal
        title="紧急召回状态"
        :visible="emergencyResultVisible"
        :footer="null"
        @cancel="closeEmergencyResult"
      >
        <a-result
          :status="emergencySuccess ? 'success' : 'error'"
          :title="emergencySuccess ? '紧急召回指令已发送' : '紧急召回指令发送失败'"
          :sub-title="emergencySuccess ? '无人机正在执行返航指令，预计返回时间: ' + emergencyETA : '请重试或联系技术支持'"
        >
          <template #extra>
            <a-button key="console" type="primary" @click="closeEmergencyResult">
              确定
            </a-button>
            <a-button key="track" v-if="emergencySuccess" @click="trackDrone">
              追踪无人机
            </a-button>
          </template>

          <div v-if="emergencySuccess">
            <a-steps :current="emergencyStep" size="small" style="margin-top: 24px">
              <a-step title="接收指令" />
              <a-step title="中断任务" />
              <a-step title="规划返航路线" />
              <a-step title="执行返航" />
              <a-step title="安全降落" />
            </a-steps>

            <div style="margin-top: 16px; background-color: #f5f5f5; padding: 16px; border-radius: 4px;">
              <p><strong>无人机状态:</strong> {{ emergencyStatus }}</p>
              <p><strong>当前高度:</strong> {{ currentDrone.altitude }}m</p>
              <p><strong>当前速度:</strong> {{ currentDrone.speed }}km/h</p>
              <p><strong>剩余电量:</strong> {{ currentDrone.battery }}%</p>
              <p><strong>预计飞行时间:</strong> {{ emergencyFlightTime }}</p>
            </div>
          </div>
        </a-result>
      </a-modal>
    </div>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'

export default {
  name: 'LiveBroadcast',
  data () {
    return {
      loading: true,
      drones: [],
      currentDroneId: null,
      isPlaying: true,
      isRecording: false,
      filterStatus: '',
      currentTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      snapshotVisible: false,
      snapshotUrl: '',
      snapshotName: '',
      snapshotRemark: '',
      contactVisible: false,
      contactMessage: '',
      emergencyModalVisible: false,
      emergencyLoading: false,
      emergencyReason: undefined,
      emergencyDescription: '',
      emergencyLevel: 'medium',
      emergencyConfirmed: false,
      emergencyResultVisible: false,
      emergencySuccess: false,
      emergencyETA: '',
      emergencyStep: 1,
      emergencyStatus: '正在执行返航指令...',
      emergencyFlightTime: '',
      timer: null
    }
  },
  computed: {
    currentDrone () {
      return this.drones.find(drone => drone.id === this.currentDroneId) || {}
    },
    filteredDrones () {
      if (!this.filterStatus) {
        return this.drones
      }
      return this.drones.filter(drone => drone.status === this.filterStatus)
    },
    activeDrones () {
      return this.drones.filter(drone => drone.status === '飞行中')
    }
  },
  mounted () {
    this.initData()
    this.timer = setInterval(() => {
      this.currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.updateDroneData()
    }, 1000)
  },
  beforeDestroy () {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    initData () {
      // 模拟加载数据
      setTimeout(() => {
        this.drones = this.generateMockDrones(10)
        this.currentDroneId = this.drones[0].id
        this.loading = false
      }, 1000)
    },
    updateDroneData () {
      // 模拟实时数据更新
      this.drones = this.drones.map(drone => {
        if (drone.status === '飞行中') {
          // 随机小幅度更新数据
          const altChange = (Math.random() - 0.5) * 2
          const speedChange = (Math.random() - 0.5) * 3
          const batteryChange = Math.random() > 0.8 ? -0.1 : 0
          const signalChange = (Math.random() - 0.5) * 2

          // 更新经纬度（模拟移动）
          const latChange = (Math.random() - 0.5) * 0.0001
          const lngChange = (Math.random() - 0.5) * 0.0001

          return {
            ...drone,
            altitude: Math.max(10, Math.min(120, drone.altitude + altChange)),
            speed: Math.max(0, Math.min(60, drone.speed + speedChange)),
            battery: Math.max(0, Math.min(100, drone.battery + batteryChange)),
            signalStrength: Math.max(0, Math.min(100, drone.signalStrength + signalChange)),
            latitude: drone.latitude + latChange,
            longitude: drone.longitude + lngChange,
            distanceTraveled: drone.distanceTraveled + (drone.speed / 3600),
            distanceRemaining: Math.max(0, drone.distanceRemaining - (drone.speed / 3600))
          }
        }
        return drone
      })
    },
    selectDrone (drone) {
      this.currentDroneId = drone.id
    },
    togglePlayPause () {
      const video = this.$refs.mainVideo
      if (this.isPlaying) {
        video.pause()
      } else {
        video.play()
      }
      this.isPlaying = !this.isPlaying
    },
    toggleRecording () {
      this.isRecording = !this.isRecording
      this.$message.success(this.isRecording ? '开始录制视频' : '视频录制已保存')
    },
    toggleFullscreen () {
      const container = this.$refs.mainVideoContainer
      if (document.fullscreenElement) {
        document.exitFullscreen()
      } else {
        container.requestFullscreen()
      }
    },
    takeSnapshot () {
      // 模拟截图功能
      this.snapshotUrl = this.currentDrone.videoUrl
      this.snapshotName = `${this.currentDrone.name}_${moment().format('YYYYMMDDHHmmss')}`
      this.snapshotVisible = true
    },
    saveSnapshot () {
      this.$message.success('截图已保存')
      this.snapshotVisible = false
    },
    handleContact () {
      this.contactVisible = true
      this.contactMessage = `您好，关于无人机 ${this.currentDrone.name}（订单：${this.currentDrone.orderSn || '无'}）的配送情况，`
    },
    sendMessage () {
      this.$message.success('消息已发送')
      this.contactVisible = false
    },
    showEmergencyModal () {
      this.emergencyModalVisible = true
      this.emergencyReason = undefined
      this.emergencyDescription = ''
      this.emergencyLevel = 'medium'
      this.emergencyConfirmed = false
    },
    handleEmergencyCancel () {
      this.emergencyModalVisible = false
    },
    handleEmergencyConfirm () {
      if (!this.emergencyReason) {
        this.$message.error('请选择召回原因')
        return
      }

      if (this.emergencyReason === 'other' && !this.emergencyDescription) {
        this.$message.error('请输入详细原因')
        return
      }

      if (!this.emergencyConfirmed) {
        this.$message.error('请确认操作')
        return
      }

      this.emergencyLoading = true

      // 模拟API请求
      setTimeout(() => {
        this.emergencyLoading = false
        this.emergencyModalVisible = false

        // 随机模拟成功或失败
        this.emergencySuccess = Math.random() > 0.1 // 90%成功率

        if (this.emergencySuccess) {
          // 计算预计返回时间
          const now = new Date()
          const minutes = Math.floor(10 + Math.random() * 20) // 10-30分钟
          now.setMinutes(now.getMinutes() + minutes)
          this.emergencyETA = now.toLocaleTimeString()
          this.emergencyFlightTime = `约${minutes}分钟`

          // 更新无人机状态
          this.currentDrone.status = '紧急返航中'

          // 启动进度更新
          this.startEmergencyProgress()
        }

        this.emergencyResultVisible = true
      }, 2000)
    },
    startEmergencyProgress () {
      // 模拟返航进度更新
      setTimeout(() => {
        this.emergencyStep = 2
        this.emergencyStatus = '已中断任务，准备返航...'
      }, 3000)

      setTimeout(() => {
        this.emergencyStep = 3
        this.emergencyStatus = '已规划返航路线，开始返航...'
      }, 6000)
    },
    closeEmergencyResult () {
      this.emergencyResultVisible = false
    },
    trackDrone () {
      // 跳转到实时地图页面
      this.$router.push({
        path: '/map/implementation',
        query: { droneId: this.currentDrone.id }
      })
    },
    getStatusColor (status) {
      const colors = {
        '飞行中': 'green',
        '待机中': 'blue',
        '返航中': 'orange',
        '充电中': 'purple',
        '维修中': 'red'
      }
      return colors[status] || 'default'
    },
    generateMockDrones (count) {
      const statuses = ['飞行中', '待机中', '充电中', '维修中']
      const statusWeights = [0.6, 0.2, 0.1, 0.1] // 权重，使飞行中的无人机更多

      const operators = [
        { name: '张三', phone: '13800138000' },
        { name: '李四', phone: '13900139000' },
        { name: '王五', phone: '13700137000' }
      ]

      return Array(count).fill().map((_, i) => {
        // 根据权重随机选择状态
        let status
        const rand = Math.random()
        if (rand < statusWeights[0]) {
          status = statuses[0]
        } else if (rand < statusWeights[0] + statusWeights[1]) {
          status = statuses[1]
        } else if (rand < statusWeights[0] + statusWeights[1] + statusWeights[2]) {
          status = statuses[2]
        } else {
          status = statuses[3]
        }

        const id = `DRONE-${String(100 + i).padStart(3, '0')}`
        const name = `无人机 ${i + 1}号`
        const altitude = status === '飞行中' ? 50 + Math.random() * 50 : 0
        const speed = status === '飞行中' ? 20 + Math.random() * 30 : 0
        const battery = 30 + Math.random() * 70
        const signalStrength = 70 + Math.random() * 30
        const latitude = 39.9 + (Math.random() - 0.5) * 0.1
        const longitude = 116.3 + (Math.random() - 0.5) * 0.1
        const distanceTraveled = status === '飞行中' ? Math.random() * 5 : 0
        const distanceRemaining = status === '飞行中' ? Math.random() * 10 : 0

        // 只有飞行中的无人机才有订单
        const hasOrder = status === '飞行中' && Math.random() > 0.2
        const orderSn = hasOrder ? `ORD${String(10000 + i).padStart(5, '0')}` : null
        const destination = hasOrder ? '北京市海淀区中关村南大街5号' : null

        // 飞行时间和预计到达时间
        const flightTime = status === '飞行中' ? `${Math.floor(Math.random() * 30)}分钟` : '-'
        const eta = status === '飞行中' ? moment().add(Math.floor(Math.random() * 30), 'minutes').format('HH:mm') : '-'

        // 随机选择操作员
        const operator = operators[Math.floor(Math.random() * operators.length)]

        // 视频URL使用不同的示例视频
        const videoUrl = `https://www.w3schools.com/html/mov_bbb.mp4`

        return {
          id,
          name,
          status,
          altitude,
          speed,
          battery,
          signalStrength,
          latitude,
          longitude,
          orderSn,
          destination,
          distanceTraveled,
          distanceRemaining,
          flightTime,
          eta,
          videoUrl,
          thumbnailUrl: `https://source.unsplash.com/100x100/?drone,${i}`,
          operatorName: operator.name,
          operatorPhone: operator.phone
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.live-broadcast-container {
  .main-video-card {
    height: 100%;

    .video-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .video-title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .main-video-container {
      position: relative;
      width: 100%;
      height: 400px;
      background-color: #000;
      overflow: hidden;

      .main-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;

        .overlay-item {
          position: absolute;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
        }

        .overlay-time {
          top: 16px;
          left: 16px;
        }

        .overlay-coordinates {
          top: 16px;
          right: 16px;
        }

        .overlay-altitude {
          bottom: 16px;
          left: 16px;
        }

        .overlay-speed {
          bottom: 16px;
          left: 100px;
        }

        .overlay-battery {
          bottom: 16px;
          right: 100px;
        }

        .overlay-signal {
          bottom: 16px;
          right: 16px;
        }
      }

      .play-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(0, 0, 0, 0.5);

        .anticon {
          font-size: 64px;
          color: #fff;
          cursor: pointer;
        }
      }
    }

    .video-info {
      margin-top: 16px;
    }
  }

  .drone-list-card {
    height: 100%;

    .drone-list {
      max-height: 300px;
      overflow-y: auto;

      .active-drone {
        background-color: #e6f7ff;
      }

      .ant-list-item {
        cursor: pointer;

        &:hover {
          background-color: #f5f5f5;
        }
      }
    }
  }

  .multi-view-card {
    .multi-view-container {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;

      .mini-video-container {
        position: relative;
        width: calc(25% - 12px);
        height: 150px;
        background-color: #000;
        overflow: hidden;
        cursor: pointer;
        border: 2px solid transparent;
        border-radius: 4px;
        &.active-mini-video {
          border-color: #1890ff;
        }
        .mini-video {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        .mini-video-overlay {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          padding: 8px;
          background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
          color: #fff;

          .mini-video-title {
            font-size: 12px;
            margin-bottom: 4px;
          }
          .mini-video-info {
            font-size: 10px;
            opacity: 0.8;
          }
        }
      }
    }
  }
}
</style>
